package com.hxk.security.service;

import com.hxk.security.bean.User;
import com.hxk.security.dao.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

@Component("userDetailsService")
public class CustomUserDetailsService implements UserDetailsService {

    @Autowired
    UserRepository userRepository;

    @Override
    public UserDetails loadUserByUsername(String login) throws UsernameNotFoundException {
        // 1. 查询用户
        User user = userRepository.findOneByLogin(login);
        if (user == null) {
            //log.warn("User: {} not found", login);
            throw new UsernameNotFoundException("User " + login + " was not found in db");
            //这里找不到必须抛异常
        }
        // 2. 设置角色
        Collection<GrantedAuthority> grantedAuthorities = new ArrayList<>();
        List<String> roles = user.getRole();
        for (String role : roles) {
            grantedAuthorities.add(new SimpleGrantedAuthority("ROLE_"+role));//注意必须加ROLE_，不然在前端不起作用
        }
        return new org.springframework.security.core.userdetails.User(login, user.getPassword(), grantedAuthorities);
    }
}